package com.teamin.web.exception;

import com.teamin.config.ErrorCode;
import com.teamin.web.model.ErrorInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.HashMap;

/**
 * 统一异常处理
 *
 * Created by bysocket on 14/03/2017.
 */
@ControllerAdvice
public class GlobalErrorInfoHandler {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 拦截异常
	 * @param exception
	 * @return
	 */
	@ExceptionHandler({Exception.class})
//	@ExceptionHandler({ MethodArgumentTypeMismatchException.class ,HttpRequestMethodNotSupportedException.class,MissingServletRequestParameterException.class ,GlobalErrorInfoException.class})
	@ResponseBody
	public ResponseEntity<Object> handleMethodArgumentTypeMismatchException(Exception exception) {
		ErrorInfo errorInfo = null;
		//传入参数类型错误异常
		if (exception instanceof MethodArgumentTypeMismatchException ) {
			errorInfo = new ErrorInfo(HttpStatus.BAD_REQUEST,ErrorCode.BAD_ARGMENTTYPE);
		} 
		//缺少必须参数
		else if ( exception instanceof MissingServletRequestParameterException) {
			errorInfo = new ErrorInfo(HttpStatus.BAD_REQUEST,ErrorCode.MISSING_PARAMETER);
		}else if(exception instanceof BindException) { //参数的校验出错
			StringBuffer sbError = new StringBuffer() ;
			BindException ec1 = (BindException) exception;
			//获取所有校验失败的参数
			ec1.getAllErrors().forEach(e->{
				sbError.append(e.getDefaultMessage()+" ") ;
			});

			errorInfo = new ErrorInfo(HttpStatus.BAD_REQUEST,ErrorCode.MISSING_PARAMETER);
			errorInfo.setMessage(sbError.toString());
		}
		//不允许的http方法
		else if (exception instanceof HttpRequestMethodNotSupportedException) {
			errorInfo = new ErrorInfo(HttpStatus.METHOD_NOT_ALLOWED,ErrorCode.METHOD_NOT_ALLOWED);
		}
		//自定义异常
		else if (exception instanceof GlobalErrorInfoException) {
			errorInfo = ((GlobalErrorInfoException) exception).getErrorInfo();
		} else {
			logger.warn(exception.getMessage(),exception);
			errorInfo = new ErrorInfo(HttpStatus.BAD_REQUEST,ErrorCode.UNKNOWN_ERROR.value(),"服务器出错,请联系管理员");
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("error", errorInfo);
		return new ResponseEntity<Object>(map, HttpStatus.valueOf(errorInfo.getStatus()));
	}

}
